package com.itheima.datastructure.demo1;

import java.util.Arrays;

public class ArrayCenterIndex {
    public static void main(String[] args) {
        System.out.println(pivotIndex(new int[]{1, 7, 3, 6, 5, 6}));
    }

    public static int pivotIndex(int[] nums) {
        // 处理空数组的情况
        if (nums == null || nums.length == 0) {
            return -1;
        }

        // 计算数组总和，使用 Arrays.stream 简化
        int totalSum = Arrays.stream(nums).sum();
        int leftSum = 0;
        int rightSum = totalSum;

        for (int i = 0; i < nums.length; i++) {
            rightSum -= nums[i];
            if (leftSum == rightSum) {
                return i;
            }
            leftSum += nums[i];
        }

        return -1;
    }
}